package com.example.eventbusdemo.eventbus;

import com.example.eventbusdemo.action.ObserverAction;
import com.example.eventbusdemo.observer.registry.ObserverRegistry;
import com.google.common.util.concurrent.MoreExecutors;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.Executor;

/**
 * @Author: zhangQi
 * @Date: 2020-10-07 19:58
 *
 * EventBus实现的是阻塞同步的观察者模式.
 * MoreExecutors.directExecutor()是Google Guava提供的工具类,看似多线程,实际单线程
 * 与AsyncEventBus做到代码逻辑统一
 */
@Component
public class EventBus {
    private Executor executor;
    private ObserverRegistry registry = new ObserverRegistry();

    public EventBus(){
        this(MoreExecutors.directExecutor());
    }

    protected EventBus(Executor executor) {
        this.executor = executor;
    }

    public void register(Object object){
        registry.register(object);
    }

    public void post(Object event) {
        List<ObserverAction> observerActions = registry.getMatchedObserverActions(event);
        for (ObserverAction observerAction : observerActions) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    observerAction.execute(event);
                }
            });
        }
    }

}
